"""
Case Type   : HTAP行列融合特性
Case Name   : GS_TOTAL_MEMORY_DETAIL函数查看max_imcs_cache设置值是否生效
Create At   : 2025/1/23
Owner       : ningyali
Description :
    1.设置enable_memory_limit为on
    2.设置max_imcs_cache为500M
    3.重启数据库
    4.查看GS_TOTAL_MEMORY_DETAIL函数
    5.清理数据环境
Expect      :
    1.执行成功
    2.执行成功
    3.执行成功
    4.执行成功，max_imcs_cache设置值生效
    5.执行成功
History     :
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class HTAP(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta_sh = CommonSH('Standby1DbUser')
        self.Constant = Constant()

    def test_trans(self):
        text = '----step1:设置enable_memory_limit为on;expect:执行成功----'
        self.log.info(text)
        guc_res = self.pri_sh.execute_gsguc(
            'set', self.Constant.GSGUC_SUCCESS_MSG,
            f'enable_memory_limit=on')
        self.assertEqual(True, guc_res, f'参数配置失败:{text}')

        text = '----step2:设置max_imcs_cache为500M; expect:执行成功----'
        self.log.info(text)
        guc_res = self.pri_sh.execute_gsguc(
            'set', self.Constant.GSGUC_SUCCESS_MSG,
            f'max_imcs_cache=500MB')
        self.assertEqual(True, guc_res, f'参数配置失败:{text}')

        text = '----step3:重启数据库; expect:执行成功----'
        self.log.info(text)
        is_restarted = self.pri_sh.restart_db_cluster()
        self.assertTrue(is_restarted, f'执行失败: {text}')

        text = '----step4:查看GS_TOTAL_MEMORY_DETAIL函数; expect:执行成功----'
        self.log.info(text)
        sql = f'select * from gs_total_memory_detail;'
        pri_res = self.pri_sh.execut_db_sql(sql)
        sta_res = self.sta_sh.execut_db_sql(sql)
        expect = r'imcstore_max_memory\s+|\s+500'
        self.assertRegex(pri_res, expect, f'执行失败: {text}')
        self.assertRegex(sta_res, expect, f'执行失败: {text}')

    def tearDown(self):
        text = '----step5:清理环境;expect:执行成功----'
        self.log.info(text)
        guc_res1 = self.pri_sh.execute_gsguc(
            'set', self.Constant.GSGUC_SUCCESS_MSG,
            f'enable_memory_limit')

        guc_res2 = self.pri_sh.execute_gsguc(
            'set', self.Constant.GSGUC_SUCCESS_MSG,
            f'max_imcs_cache')

        is_restarted = self.pri_sh.restart_db_cluster()

        self.assertEqual(True, guc_res1, f'参数配置失败:{text}')
        self.assertEqual(True, guc_res2, f'参数配置失败:{text}')
        self.assertTrue(is_restarted, f'执行失败: {text}')

        self.log.info(f'-----{os.path.basename(__file__)} end-----')
